package severlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import dao.PassageMapper;
import model.Passage;
import util.SqlSessionUtil;

/**
 * Servlet implementation class ReadServlet
 */
@WebServlet("/ReadServlet")
/**
* @author 听风寂  ，林舒馨
* @date 2020/1/8
* @ClassName ReadServlet
*/
public class ReadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		//解决后端向前端传数据中文乱码问题
		 response.setCharacterEncoding("UTF-8");
			JSONObject object=new JSONObject();
			PrintWriter out = response.getWriter();  
			String idStr = request.getSession().getAttribute("reading").toString(); 
			String userStr = request.getSession().getAttribute("user").toString(); 
			//通过id获取文章
			int id=Integer.parseInt(idStr);
			SqlSession s = SqlSessionUtil.getSqlSession();
			PassageMapper get = s.getMapper(PassageMapper.class);
			Passage find = get.selectOne(id);
			get.hitCountGrow(id);
			find = get.selectOne(id);
			System.out.println(find);
			System.out.println("id:"+id);			
			object.put("passage", find);
			if(find.getAuthor().equals(userStr)) {
				object.put("code", 1);
			}
				
			else {
				object.put("code", 0);
			}
			
			s.commit();
			String jsonStr = JSON.toJSONString(object);
			out.print(jsonStr);
			out.close();	
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}
